package com.example.person_web.core.service.impl;

import com.example.person_web.common.DateUtil;
import com.example.person_web.common.RandomNumber;
import com.example.person_web.common.WrapperResponse;
import com.example.person_web.core.dao.WebSiteDAO;
import com.example.person_web.core.dto.WebSiteDTO;
import com.example.person_web.core.entity.UserContext;
import com.example.person_web.core.entity.UserInfoDO;
import com.example.person_web.core.entity.WebSiteDO;
import com.example.person_web.core.service.WebSiteService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@Service
public class WebSiteServiceImpl implements WebSiteService {
    @Autowired
    private WebSiteDAO webSiteDAO;
    @Override
    public WrapperResponse queryWebSite() {
        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setAccount(UserContext.getUser().getAccount());
        List<WebSiteDO> list = webSiteDAO.queryWebSite(userInfoDO);
        return WrapperResponse.success(list);
    }

    @Override
    public WrapperResponse addWebSite(WebSiteDTO webSiteDTO) {
        WebSiteDO webSiteDO = new WebSiteDO();
        webSiteDO.setId(DateUtil.getCurrentDateStr()+ RandomNumber.getFourRandomNumber());
        webSiteDO.setAddress(webSiteDTO.getAddress());
        webSiteDO.setIcon(extractFaviconHref(webSiteDTO.getAddress()));
        webSiteDO.setName(webSiteDTO.getName());
        webSiteDO.setAccount(UserContext.getUser().getAccount());
        webSiteDO.setCreateTime(DateUtil.getCurrentDate());
        webSiteDO.setUpdateTime(DateUtil.getCurrentDate());
        webSiteDO.setValiFlag("1");
        int result = webSiteDAO.insertWebSite(webSiteDO);
        if(result != 0){
            return queryWebSite();
        } else {
            return WrapperResponse.fail("插入失败");
        }
    }

    @Override
    public WrapperResponse deleteWebSite(WebSiteDTO webSiteDTO) {
        WebSiteDO webSiteDO = new WebSiteDO();
        webSiteDO.setId(webSiteDTO.getId());
        int result = webSiteDAO.deleteWebSite(webSiteDO);
        if(result != 0){
            return queryWebSite();
        } else {
            return WrapperResponse.fail("删除失败");
        }
    }

    public String extractFaviconHref(String url){
        try {
            // 1. 发送请求获取网页HTML（模拟浏览器请求头，避免被拦截）
            Document document = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
                    .timeout(5000) // 超时时间5秒
                    .get();

            // 2. 筛选所有可能的favicon link标签
            // 匹配 rel="icon" 或 rel="shortcut icon"（正则匹配，忽略大小写）
            Elements linkElements = document.select("link[rel~=^icon$|^shortcut icon$]");

            if (linkElements.isEmpty()) {
                return null; // 未找到相关标签
            }

            // 3. 取第一个匹配的link标签（通常网站只定义一个）
            Element faviconLink = linkElements.first();
            String href = faviconLink.attr("href"); // 提取href属性值

            // 4. 处理相对路径（如 "/favicon.ico" 或 "static/icon.png"）
            URL baseUrl = new URL(url); // 目标网页的基础URL
            URL absoluteUrl = new URL(baseUrl, href); // 拼接为完整URL

            return absoluteUrl.toString();

        } catch (MalformedURLException e) {
            System.err.println("URL格式错误：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("请求或解析失败：" + e.getMessage());
        }
        return null;

    }
}
